package at.horario.web.component;

import org.apache.wicket.Component;
import org.apache.wicket.Session;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.IFeedback;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: azarias.muchanga
 * Date: Oct 23, 2007
 * Time: 8:44:26 AM
 * To change this template use File | Settings | File Templates.
 */
public class FieldComponentFeedbackPanel extends Label implements IFeedback {
    private IModel messagesModel;

    public FieldComponentFeedbackPanel(String id, Component filter) {
        super(id);
        messagesModel = newFeedbackMessagesModel(new ComponentFeedbackMessageFilter(filter));
        super.setModel(new Model(messagesModel) {
            public Object getObject() {
                final List messages = (List) messagesModel.getObject();
                if (messages.isEmpty()) return null;
                else {
                    final FeedbackMessage message = (FeedbackMessage) messages.get(0);
                    message.markRendered();
                    return message.getMessage();
                }
            }
        });
    }

    protected IModel newFeedbackMessagesModel(final ComponentFeedbackMessageFilter componentFeedbackMessageFilter) {
        IModel messagesModel = new AbstractReadOnlyModel() {
            // Wicket calls this method to get the actual "model object"
            // at runtime
            public Object getObject() {
                return Session.get().getFeedbackMessages().messages(componentFeedbackMessageFilter);
            }
        };
        return messagesModel;
    }

}
